package service

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"net/http"
	"smart-sensor-cloud/internal/model"
	"smart-sensor-cloud/pkg/util"
	"strconv"
)

func GetLogs(ctx *gin.Context) {
	sizeStr := ctx.DefaultQuery("size", "10")
	indexStr := ctx.DefaultQuery("page", "1")

	size, err := strconv.Atoi(sizeStr)
	if err != nil {
		ctx.Set("error", util.NewInvalidParameterError("参数转换失败"))
		return
	}
	index, err := strconv.Atoi(indexStr)
	if err != nil {
		ctx.Set("error", util.NewInvalidParameterError("参数转换失败"))
		return
	}

	logs, total, err := model.GetLogs(index, size)

	if err != nil {
		ctx.Set("error", &util.Error{
			Code:    http.StatusInternalServerError,
			Message: err.Error(),
		})
		return
	}

	util.ResponseOK(ctx, util.OKWithPayload(&util.PaginationResp{
		Size:  size,
		Index: index,
		Data:  logs,
		Total: total,
	}))
}

func DeleteLog(ctx *gin.Context) {
	idStr := ctx.Param("id")

	if idStr == "" {
		ctx.Set("error", util.NewInvalidParameterError("非法的请求参数"))
		return
	}

	id, err := strconv.Atoi(idStr)
	if err != nil {
		ctx.Set("error", util.NewInvalidParameterError("非法的请求参数"))
		return
	}

	doDelete(ctx, []int{id})
}

type (
	BatchDeleteLogsRequest struct {
		IDs []int `json:"ids"`
	}
)

func DeleteLogs(ctx *gin.Context) {
	request := new(BatchDeleteLogsRequest)

	if err := ctx.MustBindWith(request, binding.JSON); err != nil {
		ctx.Set("error", util.NewInvalidParameterError("非法的请求参数"))
		return
	}

	doDelete(ctx, request.IDs)
}

func doDelete(ctx *gin.Context, ids []int) {
	if err := model.DeleteLogByIDs(ids); err != nil {
		ctx.Set("error", &util.Error{
			Code:    http.StatusInternalServerError,
			Message: err.Error(),
		})
		return
	}

	util.ResponseOK(ctx, util.OK())
}
